<template>
  <div class="p-2">
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8" style="justify-content: end;">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="submitForm" v-hasPermi="['cemetery:feeDisclosure:add']"
              v-if="!hasData||editData">保存</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" @click="handleUpdate()"
              v-hasPermi="['cemetery:feeDisclosure:edit']" v-if="hasData">{{editData?'取消编辑':'编辑'}}</el-button>
          </el-col>
        </el-row>
      </template>
      <el-row v-if="!hasData||editData">
        <el-col :span="16">
          <el-form ref="infoFormRef" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="陵园名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入陵园名称" />
            </el-form-item>
            <el-form-item label="内容类型" prop="contextType">
              <el-radio-group v-model="form.contextType">
                <el-radio :value="1">自有信息</el-radio>
                <el-radio :value="2">外链信息</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="陵园内容" prop="context" v-if="form.contextType==1">
              <editor v-model="form.context" :min-height="192" />
            </el-form-item>
            <el-form-item label="URL" prop="context" v-if="form.contextType==2">
              <el-input v-model="form.context" placeholder="请输入URL" />
            </el-form-item>
            <el-form-item label="陵园地址" prop="location">
              <el-input v-model="form.location" placeholder="请选择陵园地址"
                :disabled="!form.latitude||!form.longitude">
                <template #append>
                  <el-icon style="cursor: pointer;" @click="chooseMap">
                    <Location />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <el-row v-else>
        <el-col :span="16">
          <el-form ref="infoFormRef" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="陵园名称" prop="name">
              {{form.name}}
            </el-form-item>
            <el-form-item label="陵园内容" prop="context" v-if="form.contextType==1">
              <div class="context" v-html="form.context"></div>
            </el-form-item>
            <el-form-item label="陵园内容" prop="context" v-if="form.contextType==2">
              <a :href="form.context" target="_blank">{{form.context}}</a>
            </el-form-item>
            <el-form-item label="陵园地址" prop="location">
              {{form.location}}
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
    <!-- 地图对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible"  v-if="dialog.visible"
      width="800px" append-to-body>
      <MapPicker @point-selected="handlePointSelected"
        :longitude="form.longitude"
        :latitude="form.latitude"/>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitLocation">确 定</el-button>
          <el-button @click="dialog.visible = false">取 消</el-button>
        </div>
      </template>
      <!-- <div v-if="currentLocation" class="location-display">
        <h3>已选择的位置:</h3>
        <p>经度: {{ currentLocation.lng }}</p>
        <p>纬度: {{ currentLocation.lat }}</p>
        <p>地址: {{ currentLocation.address }}</p>
        <button @click="submitLocation">确认选择</button>
      </div> -->
    </el-dialog>
  </div>
</template>

<script setup name="Info" lang="ts">
  import { listInfo, getInfo, delInfo, addInfo, updateInfo } from '@/api/cemetery/info';
  import { InfoVO, InfoQuery, InfoForm } from '@/api/cemetery/info/types';
  import MapPicker from '@/components/MapPicker/index.vue'

  const { proxy } = getCurrentInstance() as ComponentInternalInstance;

  const infoList = ref<InfoVO[]>([]);
  const buttonLoading = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref<Array<string | number>>([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const hasData = ref(false);
  const editData = ref(false);
  const editId = ref(null);

  const currentLocation = ref(null);

  const queryFormRef = ref<ElFormInstance>();
  const infoFormRef = ref<ElFormInstance>();

  const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
  });

  const initFormData : InfoForm = {
    id: undefined,
    name: undefined,
    context: undefined,
    longitude: undefined,
    latitude: undefined,
    location: undefined,
    contextType: 1,
  }
  const data = reactive<PageData<InfoForm, InfoQuery>>({
    form: { ...initFormData },
    queryParams: {
      pageNum: 1,
      pageSize: 1,
      name: undefined,
      contextType: undefined,
      context: undefined,
      longitude: undefined,
      latitude: undefined,
      location: undefined,
      params: {
      }
    },
    rules: {
      name: [
        { required: true, message: "陵园名称不能为空", trigger: "blur" }
      ],
      contextType: [
        { required: true, message: "内容类型不能为空", trigger: "blur" }
      ],
      context: [
        { required: true, message: "陵园内容不能为空", trigger: "blur" }
      ],
      longitude: [
        { required: true, message: "经度不能为空", trigger: "blur" }
      ],
      latitude: [
        { required: true, message: "纬度不能为空", trigger: "blur" }
      ],
      location: [
        { required: true, message: "陵园地址不能为空", trigger: "blur" }
      ],
    }
  });

  const { queryParams, form, rules } = toRefs(data);

  /** 查询陵园信息列表 */
  const getList = async () => {
    loading.value = true;
    const res = await listInfo(queryParams.value);
    infoList.value = res.rows;
    total.value = res.total;
    if (res.total > 0) {
      hasData.value = true
      form.value.name = res.rows[0].name
      form.value.contextType = res.rows[0].contextType
      form.value.context = res.rows[0].context
      form.value.location = res.rows[0].location
      editId.value = res.rows[0].id
    } else {
      hasData.value = false
    }
    loading.value = false;
  }

  /** 取消按钮 */
  const cancel = () => {
    reset();
    dialog.visible = false;
  }

  /** 表单重置 */
  const reset = () => {
    form.value = { ...initFormData };
    infoFormRef.value?.resetFields();
  }

  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
  }

  /** 多选框选中数据 */
  const handleSelectionChange = (selection : InfoVO[]) => {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }

  /** 新增按钮操作 */
  const handleAdd = () => {
    reset();
    dialog.visible = true;
    dialog.title = "添加陵园信息";
  }

  /** 修改按钮操作 */
  const handleUpdate = async (row ?: InfoVO) => {
    // reset();
    // const _id = row?.id || ids.value[0]
    // const res = await getInfo(_id);
    // Object.assign(form.value, res.data);
    // dialog.visible = true;
    // dialog.title = "修改陵园信息";
    if (editData.value) {
      editData.value = false
    } else {
      const _id = editId.value
      editData.value = true
      const res = await getInfo(_id);
      Object.assign(form.value, res.data);
    }
  }

  /** 提交按钮 */
  const submitForm = () => {
    infoFormRef.value?.validate(async (valid : boolean) => {
      if (valid) {
        buttonLoading.value = true;
        if (editId.value) {
          await updateInfo(form.value).finally(() => buttonLoading.value = false);
        } else {
          await addInfo(form.value).finally(() => buttonLoading.value = false);
        }
        proxy?.$modal.msgSuccess("操作成功");
        editData.value = false
        dialog.visible = false;
        await getList();
      }
    });
  }

  /** 删除按钮操作 */
  const handleDelete = async (row ?: InfoVO) => {
    const _ids = row?.id || ids.value;
    await proxy?.$modal.confirm('是否确认删除陵园信息编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
    await delInfo(_ids);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
  }

  /** 导出按钮操作 */
  const handleExport = () => {
    proxy?.download('cemetery/info/export', {
      ...queryParams.value
    }, `info_${new Date().getTime()}.xlsx`)
  }

  const chooseMap = () => {
    dialog.visible = true;
    dialog.title = "选择位置";
  }

  const handlePointSelected = (location) => {
    currentLocation.value = location
    console.log('选择的位置:', location)
  }
  const submitLocation = () => {
    form.value.location  = currentLocation.value.address
    form.value.longitude  = currentLocation.value.lng
    form.value.latitude  = currentLocation.value.lat
    dialog.visible = false
  }

  onMounted(() => {
    getList();
  });
</script>
<style>
  .context img{
    max-width: 100%
  }
</style>
